/*
 * @Author: zi.yang
 * @Date: 2022-02-07 10:21:18
 * @LastEditors: zi.yang
 * @LastEditTime: 2022-02-12 00:49:59
 * @Description: In User Settings Edit
 * @FilePath: \api-generator\app\public\js\home.js
 */
/* eslint-disable no-undef */
'use strict';

function renderApiDocList(data) {
  data.forEach((li, idx) => {
    const cid = `cid--${li._id}`;
    const hid = `hid-${li._id}`;
    $('#swagger-api-list').append(
      `
      <div class="card">
        <div class="card-header" id="${hid}">
          <h2 class="mb-0">
            <button
              class="btn btn-block text-left"
              type="button"
              data-toggle="collapse"
              data-target=".${cid}"
              aria-expanded="true"
              aria-controls="${cid}"
              >
              ${idx + 1}、 ${li.docName}
            </button>
          </h2>
        </div>
        <div class="collapse ${cid}" aria-labelledby="${hid}">
          <div class="card-body api-info" data-zy-id="${li._id}" >
            <ul>
              <li>文档描述：${li.description}</li>
              <li>文档地址：${li.host}</li>
              <li>文档版本：${li.version}</li>
              <li>接口数量：${li.apiDoc.length}</li>
              <li>创建时间：${li.createdAt}</li>
              <li>更新时间：${li.updatedAt}</li>
            </ul>
          </div>
        </div>
      </div>
      `
    );
  });
  /**
    data-bs-toggle="offcanvas"
              data-bs-target="#offcanvasRight"
              aria-controls="offcanvasRight"
   */
  // shown.bs.offcanvas
  $('.api-info').on('click', function() {
    const id = $(this).attr('data-zy-id');
    const d = data.find(item => item._id === id);
    console.log(d);

    // const table = $('#bootstrap-table');
    function operateFormatter() {
      return [
        '<a class="like" href="javascript:void(0)" title="Like">',
        '<i class="fas fa-heart"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="Remove">',
        '<i class="fas fa-trash"></i>',
        '</a>',
      ].join('');
    }
    $.table.init({
      id: 'bootstrap-table',
      showRefresh: false,
      singleSelect: true,
      columns: [
        { field: 'method', title: '请求方法', align: 'center', formatter: val => val.toLocaleUpperCase() },
        { field: 'operationId', title: '方法名' },
        { field: 'parameters', title: '参数列表', formatter: () => '' },
        { field: 'path', title: '请求路径' },
        { field: 'summary', title: '描述' },
        { field: 'tags', title: '标签' },
        {
          field: 'operate',
          title: 'Item Operate',
          align: 'center',
          clickToSelect: false,
          formatter: operateFormatter,
        },
      ],
      data: d.apiDoc,
    });

    // 打开
    const offcanvas = document.getElementById('offcanvasRight');
    $(offcanvas).removeClass('invisible');
    const initRight = -($(offcanvas).find('.offcanvas').width());
    $(offcanvas).find('.offcanvas').css({ right: initRight })
      .animate({ right: 0 }, 500);
    // 关闭按钮
    $('.close--offcanvas').on('click', function() {
      $(offcanvas).find('.offcanvas').animate({ right: initRight }, 500, function() {
        $(this).parent().addClass('invisible');
      });
    });

  });
}

function showSaveApiDocList() {
  $.ajax({
    url: '/api/v1/apiDoc/apiDocList',
    type: 'GET',
    success(res) {
      if (!res.success) return;
      renderApiDocList(res.data);
    },
  });
}
function fffv(data) {
  let paths = Object.keys(data.paths).map(path => path.replace(/^\//, ''));
  paths = paths.map(path => path.split('/'));
  paths = paths.filter(path => path[0] === 'api');
  const pathStrArr = paths.map(path => '/' + path.join('/'));
  const lis = [];

  pathStrArr.forEach(path => {
    const methodObj = data.paths[path];

    Object.keys(methodObj).forEach(method => {
      const { operationId, parameters, summary } = methodObj[method];
      console.log(methodObj[method]);
      lis.push({ path, method, operationId, parameters, summary });
    });
  });

  lis.forEach(li => {
    $('#swagger-api-list').append(
      `<li class="list-group-item list-group-item-action">${li.path}</li>`
    );
  });
}
$(function() {

  showSaveApiDocList();


  const swaggerUrl = 'http://47.93.210.196:8080/v2/api-docs';

  $('#get_swagger-doc').on('click', function() {
    // const swaggerUrl = $('#swagger-url').val().trim();
    // if (!swaggerUrl) {
    //   $.messageX.error('Swagger 地址不能为空！');
    //   return;
    // }

    $.ajax({
      url: '/api/v1/home/getSwaggerDoc',
      type: 'GET',
      dataType: 'json',
      data: { swaggerUrl },
      beforeSend() {
        // 禁用按钮防止重复提交
        $('#get_swagger-doc').attr({ disabled: 'disabled' });
      },
      success(res) {
        if (!res.success) {
          $.message.error(res.errorConfig.msg);
          return;
        }
        $.message.success('查询成功！');
        // $('#postman-doc').text(JSON.stringify(res.data));
        fffv(res.data);
      },
      error() {
        $.message.error('文档获取失败！');
      },
      complete() {
        $('#get_swagger-doc').removeAttr('disabled');
      },
    });
  });


  const generatorDoc = $('#generator_postman-doc');
  generatorDoc.on('click', function() {
    // const swaggerUrl = $('#swagger-url').val().trim();
    // if (!swaggerUrl) {
    //   $.messageX.error('Swagger 地址不能为空！');
    //   return;
    // }
    $('#doc-list').empty();

    $.ajax({
      url: '/api/v1/home/generateToPostman',
      type: 'GET',
      dataType: 'json',
      data: { swaggerUrl },
      beforeSend() {
        // 禁用按钮防止重复提交
        generatorDoc.attr({ disabled: 'disabled' });
      },
      success(res) {
        if (!res.success) {
          $.message.error('文档生成失败！');
          return;
        }
        $.message.success('文档生成成功！');
        const downloadPath = '/api/v1/file/downloadFileById?fileId=' + res.data._id;
        window.location.href = downloadPath;
      },
      error() {
        $.message.error('文档生成失败！');
      },
      complete() {
        generatorDoc.removeAttr('disabled');
      },
    });
  });

  $('#save_swagger-doc').on('click', function() {
    $.ajax({
      url: '/api/v1/apiDoc/addApiDoc',
      type: 'POST',
      dataType: 'json',
      data: { swaggerUrl },
      success(res) {
        if (!res.success) {
          $.message.error(res.msg);
          return;
        }
        $.message.success(res.msg);
      },
      error() {
        $.message.error('文档存储失败！');
      },
    });
  });

});
